package com.damai.action.apihandler;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.citywithincity.utils.IoUtil;
import com.citywithincity.utils.JsonUtil;
import com.damai.action.BaseServiceAction;
import com.damai.error.ApiError;
import com.damai.error.OuterError;

public class ApiHandler extends BaseServiceAction {
	
	private Map<String, IApiHandler> map = new ConcurrentHashMap<String, IApiHandler>();
	
	private static Log logger = LogFactory.getLog(ApiHandler.class);
	
	/**
	 * 接口类型定义不存在
	 */
	private static final int TYPE_NOT_EXISTS = -1;
	/**
	 * 签名错误
	 */
	private static final int SIGN_ERROR = -2;
	/**
	 * 时间戳和服务器时间相差太远
	 */
	private static final int TIME_ERROR = -3;
	/**
	 * 商户不存在
	 */
	private static final int BUSINESS_NOT_EXISTS = -4;
	
	//new BeanJsonParamGetter(type);
	
	public ApiHandler(String key) {
		super(key);
		//加载
		
	}

	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String content = IoUtil.readAndClose(new BufferedReader(request.getReader()));
		logger.info(content);
		try{
			Map<String, Object> json = JsonUtil.read(content);
			String type = (String) json.get("type");
			IApiHandler<?> action = map.get(type);
			if(action==null){
				throw new OuterError(TYPE_NOT_EXISTS, "TypeNotExists");
			}
			action.validate(json);
			Object param = action.toParam(json);
			output(response,JsonUtil.success(param));
		}catch(ApiError e){
			e.render(response.getWriter());
		}catch (Throwable e) {
			output(response, JsonUtil.alert(e.getMessage()));
		}
	}

	private void output(HttpServletResponse response,String result) throws IOException{
		logger.info(result);
		response.getWriter().print(result);
	}
}
